from fastapi import APIRouter, Depends, Request, Form, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from typing import Optional
import json
from routers.landmarks import landmarks_db, Landmark, landmark_id_counter
from routers.routes import routes_db, Route, route_id_counter

router = APIRouter()

# 设置模板目录
templates = Jinja2Templates(directory="templates")

# 管理界面路由
@router.get("/admin", response_class=HTMLResponse)
async def admin_home(request: Request):
    """管理界面首页"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    # 获取地标和路径数据
    landmarks = list(landmarks_db.values())
    routes = list(routes_db.values())

    return templates.TemplateResponse("admin/index.html", {
        "request": request,
        "user": current_user,
        "landmarks": landmarks,
        "routes": routes
    })

@router.get("/admin/api-docs", response_class=HTMLResponse)
async def admin_api_docs(request: Request):
    """API文档页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")
    return templates.TemplateResponse("admin/api_docs.html", {"request": request, "user": current_user})

# 地标管理
@router.get("/admin/landmarks", response_class=HTMLResponse)
async def admin_landmarks(request: Request):
    """地标管理页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    landmarks = list(landmarks_db.values())
    return templates.TemplateResponse("admin/landmarks.html", {"request": request, "landmarks": landmarks, "user": current_user})

@router.get("/admin/landmarks/create", response_class=HTMLResponse)
async def admin_landmark_create(request: Request):
    """创建地标页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    return templates.TemplateResponse("admin/landmark_form.html", {"request": request, "landmark": None, "user": current_user})

@router.get("/admin/landmarks/{id}/edit", response_class=HTMLResponse)
async def admin_landmark_edit(request: Request, id: int):
    """编辑地标页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    if id not in landmarks_db:
        raise HTTPException(status_code=404, detail="地标未找到")
    landmark = landmarks_db[id]
    return templates.TemplateResponse("admin/landmark_form.html", {"request": request, "landmark": landmark, "user": current_user})

@router.post("/admin/landmarks/save")
async def admin_landmark_save(
    request: Request,
    id: Optional[int] = Form(None),
    name: str = Form(...),
    lat: float = Form(...),
    lng: float = Form(...),
    summary: str = Form(...),
    details: str = Form(...),
    media: Optional[str] = Form(None)
):
    """保存地标"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    media_list = []
    if media:
        media_list = json.loads(media)

    if id:  # 更新
        if int(id) not in landmarks_db:
            raise HTTPException(status_code=404, detail="地标未找到")
        landmark = Landmark(
            id=int(id),
            name=name,
            lat=lat,
            lng=lng,
            summary=summary,
            details=details,
            media=media_list
        )
        landmarks_db[int(id)] = landmark
    else:  # 创建
        global landmark_id_counter
        landmark = Landmark(
            id=landmark_id_counter,
            name=name,
            lat=lat,
            lng=lng,
            summary=summary,
            details=details,
            media=media_list
        )
        landmarks_db[landmark_id_counter] = landmark
        landmark_id_counter += 1

    return RedirectResponse(url="/admin/landmarks", status_code=303)

@router.get("/admin/landmarks/{id}/delete")
async def admin_landmark_delete(request: Request, id: int):
    """删除地标"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    if int(id) not in landmarks_db:
        raise HTTPException(status_code=404, detail="地标未找到")
    del landmarks_db[int(id)]
    return RedirectResponse(url="/admin/landmarks", status_code=303)

# 路径管理
@router.get("/admin/routes", response_class=HTMLResponse)
async def admin_routes(request: Request):
    """路径管理页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    routes = list(routes_db.values())
    return templates.TemplateResponse("admin/routes.html", {"request": request, "routes": routes, "user": current_user})

@router.get("/admin/routes/create", response_class=HTMLResponse)
async def admin_route_create(request: Request):
    """创建路径页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    landmarks = list(landmarks_db.values())
    return templates.TemplateResponse("admin/route_form.html", {"request": request, "route": None, "landmarks": landmarks, "user": current_user})

@router.get("/admin/routes/{id}/edit", response_class=HTMLResponse)
async def admin_route_edit(request: Request, id: int):
    """编辑路径页面"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    if int(id) not in routes_db:
        raise HTTPException(status_code=404, detail="路径未找到")
    route = routes_db[int(id)]
    landmarks = list(landmarks_db.values())
    return templates.TemplateResponse("admin/route_form.html", {"request": request, "route": route, "landmarks": landmarks, "user": current_user})

@router.post("/admin/routes/save")
async def admin_route_save(
    request: Request,
    id: Optional[int] = Form(None),
    name: str = Form(...),
    landmarks: Optional[str] = Form(None)
):
    """保存路径"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    landmark_ids = []
    if landmarks:
        landmark_ids = [int(x) for x in json.loads(landmarks)]

    if id:  # 更新
        if int(id) not in routes_db:
            raise HTTPException(status_code=404, detail="路径未找到")
        route = Route(
            id=int(id),
            name=name,
            landmarks=landmark_ids
        )
        routes_db[int(id)] = route
    else:  # 创建
        global route_id_counter
        route = Route(
            id=route_id_counter,
            name=name,
            landmarks=landmark_ids
        )
        routes_db[route_id_counter] = route
        route_id_counter += 1

    return RedirectResponse(url="/admin/routes", status_code=303)

@router.get("/admin/routes/{id}/delete")
async def admin_route_delete(request: Request, id: int):
    """删除路径"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        return RedirectResponse(url="/login")

    if int(id) not in routes_db:
        raise HTTPException(status_code=404, detail="路径未找到")
    del routes_db[int(id)]
    return RedirectResponse(url="/admin/routes", status_code=303)
